package com.hslxy.niukewang.quartz;

import com.hslxy.niukewang.entity.DiscussPost;
import com.hslxy.niukewang.service.DiscussPostService;
import com.hslxy.niukewang.service.ElasticsearchService;
import com.hslxy.niukewang.service.LikeService;
import com.hslxy.niukewang.util.Constant;
import com.hslxy.niukewang.util.RedisKeyUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.swing.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//定时计算帖子热度
public class PostScoreRefreshJob implements Job , Constant {
    private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private ElasticsearchService elasticsearchService;

    private static final Date epoch;

    static {
        try {
            epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-08-01 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String postScoreKey = RedisKeyUtil.getPostScoreKey();
        BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(postScoreKey);
        if (boundSetOperations.size() == 0){
            logger.info("无帖子需要计算分数");
            return;
        }
        logger.info("正在刷新分数" + boundSetOperations.size());
        while (boundSetOperations.size() > 0){
            this.refresh((Integer)boundSetOperations.pop());
        }
        logger.info("计算完了帖子分数");
    }

    private void refresh(Integer postId) {
        DiscussPost discussPost = discussPostService.findDiscussPost(postId);
        if(discussPost == null){
            logger.error("该帖子不存在:id = " + postId);
            return;
        }
        boolean wonderful = discussPost.getStatus() == 1;
        int commentCount = discussPost.getCommentCount();
        Long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, postId);
        double w = (wonderful?75:0) + commentCount * 10 + likeCount * 2;
        double score = Math.log10(Math.max(w, 1)) + (discussPost.getCreateTime().getTime() - epoch.getTime())/ (1000*3600*24);
        discussPostService.updateScore(postId, score);
        discussPost.setScore(score);
        elasticsearchService.saveDiscussPost(discussPost);
    }
}
